<?php
/**
 * Created by PhpStorm.
 * User: 秋刀鱼
 * Date: 2018/7/28
 * Time: 15:35
 */


namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use yii\db\query;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;
use yii\web\models;
use \common\helps\tools;//使用工具类
use yii\db\ActiveRecord;
use yii\db\Connection;

/**
 * Principal controller
 */
class PrincipalController extends Controller
{

    public function init()
    {
        $this->enableCsrfValidation = false;
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * title 首页列表
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndexlist()
    {
        return $this->render('list');
    }

    /**
     * 渲染添加页面
     */
    public function actionAddproject()
    {
        return $this->render('addproject');
    }

    /**
     * 渲染详情页面
     */
    public function actionProjectdetail()
    {
        return $this->render('projectdetail');
    }

    /**
     * title 添加 申报项目
     * Displays homepage.
     *
     * @return string
     */
    public function actionAdddoproject()
    {
        header('Access-Control-Allow-Origin:*');

        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('9','token过期,请重新登录',[$checkToken]);
        }
        $time = date('Y-m-d H:i:s',time());
        $special_project = new \app\models\SpecialProject;
        $list = $special_project->addProject($time,$uid);
        //最新id
        $lastId = $special_project->lastId();
        //添加special_project_child
        $add_child = $special_project->addChild($lastId['id'],$time);
        if (!$add_child) {
            return tools::ajax_return_error('2', '保存失败', ['2']);
        }


        if($list){
            return tools::ajax_return('0','添加成功',$lastId['id']);
        }else{
            return tools::ajax_return('1','添加失败',[]);
        }

    }


    /**
     * title 列表
     * @return string
     */
    public function actionList()
    {
        header('Access-Control-Allow-Origin:*');
        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('9','token过期,请重新登录',[$checkToken]);
        }


        $special_project = new \app\models\SpecialProject;
        $list = $special_project->projectList($uid);
        if($list){
            return tools::ajax_return('0','成功',$list);
        }else{
            return tools::ajax_return('0','成功',[]);
        }


    }

    /**
     * 保存申报项目
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionSaveproject()
    {

        header('Access-Control-Allow-Origin:*');

        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('9','token过期,请重新登录',[$checkToken]);
        }

//        $uuid = tools::createUuid();

        $id = $post['id'];//主表id
        $type = $post['type'];
        $item_no = $post['item_no'];
        $project_type = $post['project_type'];//项目类型
        $project_principal = $post['project_principal'];//项目负责人
        $project_name = $post['project_name'];//项目名称
        $project_name_child = $post['project_name_child'];//子项目名称
        $begin_time = $post['begin_time'];//开始时间
        $end_time = $post['end_time'];//结束时间
        $belong_company = $post['belong_company'];//所属研究单位
        $longitude = $post['longitude'];//经度
        $latitude = $post['latitude'];//纬度
        $budget_money = $post['budget_money'];//项目预算金额
        $grant_way = $post['grant_way'];//发放方式
        $status = $post['status'];//1添加 2保存提交

        $thesis = $post['thesis'];//论文


        if($type != 1 && $type != 2){
            return tools::ajax_return_error('2','请传正确type',['type不正确']);
        }

        //调用主表项目model
        $special_project = new \app\models\SpecialProject;
        //判断 添加还是保存
        if($status == 1) {
            if (!empty($project_name)) {
                if ($type == 1) {
                    //是否已有数据
                    $checkRepetition = $special_project->checkRepetition($project_name, $belong_company);
                    if ($checkRepetition) {
                        return tools::ajax_return_error('2', '项目名称,所属单位已存在', []);
                    }
                } else {
                    //是否已有数据
                    $checkRepetition = $special_project->checkRepetition($project_name_child, $belong_company);
                    if ($checkRepetition) {
                        return tools::ajax_return_error('2', '项目名称,所属单位已存在', []);
                    }
                }
            }
        }

        $update_time = date('Y-m-d H:i:s',time());

        //保存special_project
        $special_project_add = $special_project->saveProject($id,$project_type, $begin_time, $end_time, $grant_way, $update_time, $type,$uid,1);
        if (!$special_project_add) {
            return tools::ajax_return_error('2', '保存失败', ['1.1']);
        }
        //1一家单位 2多家单位
        if($type == 2){
            $ParentId = $special_project->ParentId($id);
                if (!$ParentId) {
                    return tools::ajax_return_error('2', '上级名称不正确或者不存在', []);
                }
                $project_name = $project_name . '-' . $project_name_child;
                //添加special_project_child
                $add_child = $special_project->addChild($id, $update_time, $item_no, $project_principal, $budget_money, $project_name, $belong_company, $longitude, $latitude, $pid = $ParentId['id']);
                if (!$add_child) {
                    return tools::ajax_return_error('2', '保存失败', ['2']);
                }
        }else {


            //添加special_project_child
            $special_project_add_child = $special_project->addChild($id, $update_time, $item_no, $project_principal, $budget_money, $project_name, $belong_company, $longitude, $latitude, $pid = 0);
            if (!$special_project_add_child) {
                return tools::ajax_return_error('2', '保存失败', ['2']);
            }


        }

        //论文类型 论文数量
//        $thesis = [['project_id'=>1,'type_count'=>1,'type'=>1,'create_time'=>'2018-07-31 13:35:57','type_id'=>1],['project_id'=>1,'type_count'=>1,'type'=>1,'create_time'=>'2018-07-31 13:35:57','type_id'=>1]];

//        $thesisArr = explode(',',$thesis);
        $thesis = json_decode($thesis,true);


        //添加type_num
        $type_num = new \app\models\TypeNum;

        //论文
        $a = '';
        //清除之前的
        $query = new \yii\db\Query();
        $table = 'data_yii.type_num';
        $num = $query->select(['id'])->from($table)->where(['project_id'=>$id])->one();
        if($num) {
            $del = Yii::$app->db->createCommand()->delete($table, "project_id = '$id'")->execute();
            if (!$del) {
                return 0;
            }
        }
        //调用添加
        foreach($thesis as $tv) {
            if (!empty($tv) && !empty($tv['type_id']) && !empty($tv['type_count'])) {
                $addNum = $type_num->addNum($id, $tv['type_count'], $tv['type'], $update_time, $tv['type_id']);
                if (!$addNum) {
                    $a = 1;

                }
                if ($a == 1) {
                    return tools::ajax_return_error('2', '保存失败', ['3']);
                }

            }
        }

        return tools::ajax_return('0','保存成功',[]);


    }


    /**
     * title 提交申报项目
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionSubmitproject()
    {
        header('Access-Control-Allow-Origin:*');

        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('9','token过期,请重新登录',[$checkToken]);
        }

        $id = $post['id'];
        $type = $post['type'];
        $item_no = $post['item_no'];
        $project_type = $post['project_type'];//项目类型
        $project_principal = $post['project_principal'];//项目负责人
        $project_name = $post['project_name'];//项目名称
        $project_name_child = $post['project_name_child'];//子项目名称
        $begin_time = $post['begin_time'];//开始时间
        $end_time = $post['end_time'];//结束时间
        $belong_company = $post['belong_company'];//所属研究单位
        $longitude = $post['longitude'];//经度
        $latitude = $post['latitude'];//纬度
        $budget_money = $post['budget_money'];//项目预算金额
        $grant_way = $post['grant_way'];//发放方式
        $thesis = $post['thesis'];//论文 专利数组
        $status = $post['status'];//1添加 2保存提交



        //验证
        if(empty($item_no)){
            return tools::ajax_return_error('2', '课题号不能为空', []);
        }
        if(empty($project_type)){
            return tools::ajax_return_error('2', '项目类型不能为空', []);
        }
        if(empty($project_principal)){
            return tools::ajax_return_error('2', '项目负责人不能为空', []);
        }
        if(empty($project_name)){
            return tools::ajax_return_error('2', '项目名称不能为空', []);
        }
        if(empty($begin_time)){
            return tools::ajax_return_error('2', '请选择开始时间', []);
        }
        if(empty($end_time)){
            return tools::ajax_return_error('2', '请选择结束时间', []);
        }
        if(empty($belong_company)){
            return tools::ajax_return_error('2', '所属研究单位不能为空', []);
        }
        if(empty($longitude)){
            return tools::ajax_return_error('2', '经度?', []);
        }
        if(empty($latitude)){
            return tools::ajax_return_error('2', '纬度?', []);
        }
        if(empty($budget_money)){
            return tools::ajax_return_error('2', '请输入预算金额', []);
        }
        if(empty($grant_way)){
            return tools::ajax_return_error('2', '请选择发放方式', []);
        }

        if($type != 1 && $type != 2){
            return tools::ajax_return_error('2','请传正确type',['type不正确']);
        }

        //调用主表项目model
        $special_project = new \app\models\SpecialProject;
        //判断 添加还是保存
        if($status == 1) {
            if (!empty($project_name)) {
                if ($type == 1) {
                    //是否已有数据
                    $checkRepetition = $special_project->checkRepetition($project_name, $belong_company);
                    if ($checkRepetition) {
                        return tools::ajax_return_error('2', '项目名称,所属单位已存在', []);
                    }
                } else {
                    //是否已有数据
                    $checkRepetition = $special_project->checkRepetition($project_name_child, $belong_company);
                    if ($checkRepetition) {
                        return tools::ajax_return_error('2', '项目名称,所属单位已存在', []);
                    }
                }
            }
        }

        $update_time = date('Y-m-d H:i:s',time());

        //添加special_project
        $special_project_add = $special_project->saveProject($id,$project_type, $begin_time, $end_time, $grant_way, $update_time, $type,$uid,2);
        if (!$special_project_add) {
            return tools::ajax_return_error('2', '提交失败', ['1.1']);
        }
        //1一家单位 2多家单位
        if($type == 2){
            //查找上级
            $ParentProject = $special_project->ParentProject($project_name);
            if (empty($ParentProject)) {
                return tools::ajax_return_error('2', '上级名称不正确或者不存在', []);
            }
            $project_name = $project_name . '-' . $project_name_child;
            //添加special_project_child
            $add_child = $special_project->addChild($id, $update_time, $item_no, $project_principal, $budget_money, $project_name, $belong_company, $longitude, $latitude, $pid = $ParentProject['id']);
            if (!$add_child) {
                return tools::ajax_return_error('2', '提交失败', ['2']);
            }
        }else {

            //添加special_project_child
            $special_project_add_child = $special_project->addChild($id, $update_time, $item_no, $project_principal, $budget_money, $project_name, $belong_company, $longitude, $latitude, $pid = 0);
            if (!$special_project_add_child) {
                return tools::ajax_return_error('2', '提交失败', ['2.2']);
            }


        }

        //论文类型 论文数量
//        $thesis = [['project_id'=>1,'type_count'=>1,'type'=>1,'create_time'=>'2018-07-31 13:35:57','type_id'=>1],['project_id'=>1,'type_count'=>1,'type'=>1,'create_time'=>'2018-07-31 13:35:57','type_id'=>1]];

//        $thesisArr = explode(',',$thesis);
        $thesis = json_decode($thesis,true);


        //添加type_num
        $type_num = new \app\models\TypeNum;

        //论文
        $a = '';
        //清除之前的
        $query = new \yii\db\Query();
        $table = 'data_yii.type_num';
        $num = $query->select(['id'])->from($table)->where(['project_id'=>$id])->one();
        if($num) {
            $del = Yii::$app->db->createCommand()->delete($table, "project_id = '$id'")->execute();
            if (!$del) {
                return 0;
            }
        }
        //调用添加
        foreach($thesis as $tv) {
            if (!empty($tv) && !empty($tv['type_id']) && !empty($tv['type_count'])) {
                $addNum = $type_num->addNum($id, $tv['type_count'], $tv['type'], $update_time, $tv['type_id']);
                if (!$addNum) {
                    $a = 1;

                }
                if ($a == 1) {
                    return tools::ajax_return_error('2', '提交失败', ['3']);
                }

            }
        }

        return tools::ajax_return('0','提交成功',[]);



        return tools::ajax_return('0','提交成功',[]);



    }


    /**
     * title 详情
     * @return string
     */
    public function actionDetailproject()
    {
        header('Access-Control-Allow-Origin:*');
        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return_error('9','token过期,请重新登录',[$checkToken]);
        }


        $query =  new \yii\db\Query();
        $id = $post['id'];
        $status = $post['status'];
        if($status != 1 && $status != 2){
            return tools::ajax_return_error('2','请传正确状态',[]);
        }

        $specialProject = new \app\models\SpecialProject;
        $detail = $specialProject->detail($id,$status);


            //发放方式
        $grank_way = $query->select(['id','content','create_time','update_time'])->from('data_yii.grank_way')->where(['id'=>$detail['grant_way']])->one();
            if(!empty($grank_way['content'])) {
                $detail['way'] = $grank_way['content'];
            }else{
                $detail['way'] = '';
            }

            //论文
            $typeNum = new \app\models\TypeNum;
            $selectNum = $typeNum->selectNum($id);


            if(!empty($selectNum)) {
                foreach($selectNum as $k => $v) {
                    $detail['num'][$k]['type_count'] = $v['type_count'];
                    $detail['num'][$k]['type'] = $v['type'];
                    $detail['num'][$k]['type_id'] = $v['type_id'];
                    $detail['num'][$k]['content'] = $v['content'];
                }
            }else{
                $detail['num'] = [];
            }



            return tools::ajax_return('0','成功',$detail);


    }


    /**
     * title 查询 发放方式
     * @return string
     */
    public function actionSelectgrank()
    {
        header('Access-Control-Allow-Origin:*');

        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('9','token过期,请重新登录',[$checkToken]);
        }

        //查询
        $GrankWay = new \app\models\SpecialOther();
        $selectGrank = $GrankWay->selectGrank();
        if($selectGrank){
            return tools::ajax_return('0','成功',$selectGrank);
        }else{
            return tools::ajax_return('0','成功',[]);
        }


    }


    /**
     * title 查询 论文类型
     * @return string
     */
    public function actionSelectpatent()
    {
        header('Access-Control-Allow-Origin:*');
        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('9','token过期,请重新登录',[$checkToken]);
        }

        //查询
        $GrankWay = new \app\models\SpecialOther();
        $patent = $GrankWay->selectPatent();
        if($patent){
            return tools::ajax_return('0','成功',$patent);
        }else{
            return tools::ajax_return('0','成功',[]);
        }


    }


    /**
     * title 查询专利类型
     * @return string
     */
    public function actionSelectthesis()
    {
        header('Access-Control-Allow-Origin:*');
        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('9','token过期,请重新登录',[$checkToken]);
        }

        //查询
        $GrankWay = new \app\models\SpecialOther();
        $thesis = $GrankWay->selectThesis();
        if($thesis){
            return tools::ajax_return('0','成功',$thesis);
        }else{
            return tools::ajax_return('0','成功',[]);
        }
    }



    /**
     * title 搜索 项目名称
     * @return string
     */
    public function actionSearch()
    {
        header('Access-Control-Allow-Origin:*');
        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return('9','token过期,请重新登录',[$checkToken]);
        }


        //搜索
        $project_name = $post['project_name'];
        $special_project = new \app\models\SpecialProject;
        $list = $special_project->projectSearch($project_name);
        if($list){
            return tools::ajax_return('0','成功',$list);
        }else{
            return tools::ajax_return('0','成功',[]);
        }



    }

    /**
     * title 删除
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionDelproject()
    {
        header('Access-Control-Allow-Origin:*');
        $post = Yii::$app->request->post();
        $uid = $post['uid'];
        $token = $post['token'];
        //token验证
        $checkToken = tools::checkToken('admin_'.$uid,$token);
        if($checkToken != 4){
            return tools::ajax_return_error('9','token过期,请重新登录',[$checkToken]);
        }

        $id = $post['id'];

        $special_project = new \app\models\SpecialProject;
        $del = $special_project::delProject($id);

        if($del == 1){
            return tools::ajax_return_error('1','参数错误',[]);
        }else{
            return tools::ajax_return('0','成功',[]);
        }




    }






}